#pragma once

#include<iostream>
#include<string>
#include<cstdarg>
#include<ctime>
#include<fstream>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include"LockGuard.hpp"

enum
{
    Debug = 0,
    Info,       // 正常信息
    Warning,    // 告警
    Error,      // 错误
    Fatal       // 致命错误
};

enum
{
    Screen = 0,    // 向显示器打印
    OneFile,        // 向一个文件打印
    ClassFile       // 向多个文件打印
};

// 将日志等级转换为string
std::string LevelToString(int level)
{
    switch(level)
    {
    case Debug:
        return "Debug";
    case Info:
        return "Info";
    case Warning:
        return "Warning";
    case Error:
        return "Error";
    case Fatal:
        return "Fatal";
    default:
        return "Unknown";
    }
}

const int defaultstyle = Screen;                // 默认风格是向显示器打印
const std::string default_filename = "log."; // 默认文件名
const std::string logdir = "log";              // 默认日志文件夹

class Log
{
public:
    Log()
        :_style(defaultstyle)
        ,_filename(default_filename)
    {
        mkdir(logdir.c_str(), 0775);
        pthread_mutex_init(&_mutex, nullptr);
    }

    void Enable(int style)
    {
        _style = style;
    }

    std::string TimeStampExLocalTime()
    {
        time_t currtime = time(nullptr);
        struct tm *curr = localtime(&currtime);
        char time_buffer[128];
        snprintf(time_buffer, sizeof(time_buffer), "%d-%d-%d %d:%d:%d", \
            curr->tm_year+1900, curr->tm_mon+1, curr->tm_mday,\
            curr->tm_hour, curr->tm_min, curr->tm_sec);
        return time_buffer;
    }

    void WriteLogToOneFile(const std::string &logname, const std::string &message)
    {
        // std::ofstream out(logname);
        // if(!out.is_open())  return;

        // out.write(message.c_str(), message.size());
        // out.close();
        umask(0);
        int fd = open(logname.c_str(), O_CREAT | O_WRONLY | O_APPEND, 0666);
        if(fd < 0) return;
        write(fd, message.c_str(), message.size());
        close(fd);
    }

    void WriteLogToClassFile(const std::string &levelstr, const std::string &message)
    {
        std::string logname = logdir;
        logname += "/";
        logname += _filename;
        logname += levelstr;
        WriteLogToOneFile(logname, message);
    }

    void WriteLog(const std::string &levelstr, const std::string &message)
    {
        switch(_style)
        {
            case Screen:
                std::cout << message;
                break;
            case OneFile:
                WriteLogToClassFile("all", message);
                break;
            case ClassFile:
                WriteLogToClassFile(levelstr, message);
                break;
            default:
                break;
        }
    }

    void LogMessage(int level, const char* format, ...) // 类C的一个日志接口
    {
        char rightbuffer[1024];
        va_list args;    // 这是一个char *类型（或者void *）的指针
        va_start(args, format);     // 让arg指向可变部分

        vsnprintf(rightbuffer, sizeof(rightbuffer), format, args);  // 将可变部分按照指定格式写入到content中
        va_end(args);   // 释放args, args = nullptr

        char leftbuffer[1024];
        std::string levelstr = LevelToString(level);
        std::string currtime = TimeStampExLocalTime();      // 获取当前时间
        std::string idstr = std::to_string(getpid());
        
        snprintf(leftbuffer, sizeof(leftbuffer), "[%s][%s][%s] ", \
            levelstr.c_str(), currtime.c_str(), idstr.c_str());
        
        std::string loginfo = leftbuffer;
        loginfo += rightbuffer;
        
        {
            LockGuard lockguard(&_mutex);
            WriteLog(levelstr, loginfo);
        }
    }

    ~Log()
    {}
private:
    int _style;
    std::string _filename;
    pthread_mutex_t _mutex;
};


// 配置log
Log lg;

class Config
{
public:
    Config()
    {
        // 在此配置
        lg.Enable(Screen);
    }

    ~Config()
    {}
};

Config config;